package com.zjitc.order;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/18 13:46
 * @description: 模拟消费者进行下订单
 */
public class SimulateCustomer {

  private ExecutorService service = Executors.newFixedThreadPool(30);
  private JedisPool pool;
  private static final String SECOND_KILL_PRODUCT_NAME = "SECOND_KILL_U";
  private static final int CUSTOMER_COUNT = 5;
  private static final int SECOND_KILL_PRODUCT_COUNT = 200;

  /**
   * 构造的初始化函数
   */
  public SimulateCustomer() {
    // redis的配置
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(20);
    config.setMinIdle(10);
    config.setBlockWhenExhausted(true);

    // redis的连接池
    this.pool = new JedisPool(config, "localhost");

    // 初始化秒杀商品在redis中的信息 KEY = SECOND_KILL_U, VALUE= 200
    try (Jedis jedis = this.pool.getResource()) {
      jedis.set(SECOND_KILL_PRODUCT_NAME, Integer.toString(SECOND_KILL_PRODUCT_COUNT));
    }
  }

  public void start() {
    // 模拟30个人，持续不断的进行购买
    for (int i = 0; i < CUSTOMER_COUNT; i++) {
      service.submit(()->{
        while (true) {
          Thread.sleep(200);

          try (Jedis jedis = this.pool.getResource()) {
            // 查询redis中，还剩下多少商品，如果remain返回的值大于0，表示用户买到了商品
            Long remainCount = jedis.decr(SECOND_KILL_PRODUCT_NAME);
            if (remainCount >= 0) {
              // 当用户买到商品之后，将用户的买到的商品信息投入到队列中去，提供给后台线程进行数据库的修改
              QueueOrderInfo.Instance.add(new OrderInfo(Long.toString(remainCount), 1));
            }

            if (remainCount == 0) {
              System.out.println("所有的商品已经卖光了");
            }
          }
        }
      });
    }
  }

  public static void main(String[] args) throws InterruptedException {
    SimulateCustomer simulateCustomer = new SimulateCustomer();
    simulateCustomer.start();

    QueueOrderInfoThread thread = new QueueOrderInfoThread();
    thread.start();
  }
}
